<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 使用工具组件 -->
      <page-tools show-before>
        <!-- <template v-slot:before>共166条记录</template> -->
        <!-- <template #before>共166条记录</template> -->
        <!-- <template slot="before">共166条记录</template> -->
        <span slot="before">共{{ query.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import?type=employees')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column width="100" type="index" label="序号" sortable />
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column width="150" label="头像" align="center">
            <template slot-scope="{ row }">
              <img
                slot="reference"
                :src="row.staffPhoto"
                v-imageError="require('@/assets/common/head.jpg')"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showCodeDialogHandle('https://www.kuaijiankj.com')"
              />
            </template>
          </el-table-column>
          <el-table-column width="150" label="手机号码" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column width="200" label="聘用形式" sortable prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column width="150" label="部门" sortable prop="departmentName" />
          <el-table-column width="200" label="入职时间" sortable prop="timeOfEntry">
            <!-- 插槽来处理时间+过滤器 -->
            <template slot-scope="{ row }">{{ row.timeOfEntry | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
          </el-table-column>
          <el-table-column width="200" label="在职状态" prop="enableState" :formatter="formatEnableState" />
          <el-table-column width="120" label="账号状态" prop="inServiceStatus">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.inServiceStatus === 1" active-color="#13ce66" />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button :disabled="!checkPermission('point-role-assign')" type="text" size="small" @click="showAssignRole(row.id)">角色</el-button>
              <el-button :disabled="!checkPermission('point-user-delete')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
              <el-button size="small" type="text" @click="$router.push(`/employees/print/${row.id}?type=personal`)">打印员工基本信息</el-button>
              <el-button size="small" type="text" @click="$router.push(`/employees/print/${row.id}?type=job`)">打印员工岗位信息信息</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination :current-page="query.page" :total="query.total" :page-size="query.size" layout="prev, pager, next" @current-change="handleCurrentChange" />
        </el-row>
      </el-card>
    </div>
    <!-- 添加/修改员工 -->
    <!-- <edit-employees ref="editEmployeeRef" :list="list" @get-new-employees="getEmployeeList" /> -->
    <edit-employees ref="editEmployeeRef" :list="list" />
    <!-- 显示图片的二位对话框 -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog" @opened="showQrCode" @close="img_url = ''">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 给员工分配角色 -->
    <assign-role ref="assignRoleRef" />
  </div>
</template>

<script>
import { getEmployeeListApi, delEmployeeApi } from '@/api/employees'
import employees from '@/api/constant/employees'
import EditEmployees from './components/edit-employees.vue'
import AssignRole from './components/assign-role.vue'
// 导入formatDate()来进行格式化时间日期
import { formatDate } from '@/filters'
// 导入QRCode
import QRCode from 'qrcode'
// mixin就是一个对象，里面可以写跟vue组件一样的选项
/* const obj = {
  data() {
    return {
      name: '张三'
    }
  },
  methods: {
    btn() {
      console.log(123)
    }
  },
  created() {
    console.log(456)
  }
} */
// import checkPermission from '@/mixins/checkPermission'
export default {
  components: {
    EditEmployees,
    AssignRole
  },
  // 局部混入
  // mixins: [checkPermission],
  data() {
    return {
      // 员工数据
      list: [],
      // 查询条件
      query: {
        page: 1,
        size: 6,
        total: 0
      },
      // 控制图片对话框的显示
      showCodeDialog: false,
      // 要被生成图片url地址
      img_url: ''
    }
  },
  created() {
    // 获取员工列表数据
    this.getEmployeeList()
  },
  methods: {
    // 点击角色分配按钮，打开角色分配页面
    showAssignRole(userId) {
      this.$refs.assignRoleRef.open(userId)
    },
    // 打开图片对话框
    showCodeDialogHandle(url) {
      this.showCodeDialog = true
      this.img_url = url
    },
    // 打开图片对话框的触发
    showQrCode() {
      if (this.img_url) {
        // 生成图片二维码
        QRCode.toCanvas(this.$refs.myCanvas, this.img_url)
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 获取员工列表数据
    async getEmployeeList() {
      const { total, rows } = await getEmployeeListApi(this.query)
      console.log(rows)
      this.list = rows
      this.query.total = total
    },
    // 监听页面改变事件
    handleCurrentChange(page) {
      this.query.page = page
      this.getEmployeeList()
    },
    // 格式化显示聘用形式
    formatEmployment(row) {
      const result = employees['hireType'].find(item => item.id === row.formOfEmployment)
      return result ? result.value : '未知状态'
    },
    // 格式化显示在职状态
    formatEnableState(row, column, cellvalue) {
      const result = employees['workingState'].find(item => +item.id === cellvalue)
      return result ? result.value : '未知状态'
    },
    // 删除员工
    async delEmployee(id) {
      try {
        // 确定删除
        await this.$confirm('您确定要删除该员工吗')
        await delEmployeeApi(id)
        this.$message.success('删除成功')
        this.getEmployeeList()
      } catch (err) {
        // 取消
      }
    },
    // 显示添加/修改对话框
    showEditEmployeeDialog() {
      // 调用子组件的open()方法
      this.$refs.editEmployeeRef.open()
    },
    // 导出excel数据
    exportData() {
      /*
      // 范例
      excel.export_json_to_excel({
          header: ['姓名', '年龄', '性别'],
          data: [
            ['张三', 28, '男'],
            ['李四', 23, '男'],
            ['王五', 24, '男']
          ],
          filename: 'employees'
        }) */

      // 表头对应关系
      // headeds对象的值必须和数据对象的属性名保持一一对应
      // [{username:'张三',mobile:1992992920,....}]
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      // 按需导出
      import('@/vendor/Export2Excel').then(async excel => {
        // 导出的所有的数据，所有每页显示的条数就是总记录数
        const { rows } = await getEmployeeListApi({ page: 1, size: this.query.total })
        const data = this.formatJson(headers, rows)
        // 处理数据
        excel.export_json_to_excel({
          header: Object.keys(headers),
          // 如果需要导出复杂的表头（如笔记效果）
          multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']],
          // 合并项
          merges: ['A1:A2', 'B1:F1', 'G1:G2'],
          data,
          filename: 'employees'
        })
      })
    },
    // 处理要导出的数据成excel导出所需要的格式
    formatJson(headers, rows) {
      // headers:{'姓名':'username','年龄':'age'}
      // rows:[{username:'张三',age:28},{username:'李四',age:23]
      // 需要的数据：[['张三',28],['李四',23] ]
      const arr = rows.map(item => {
        return Object.keys(headers).map(key => {
          // 处理入职时间和转正时间
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]]) // 返回格式化之前的时间
          } else if (headers[key] === 'formOfEmployment') {
            // 聘用形式
            const en = employees['hireType'].find(obj => obj.id === item[headers[key]])
            return en ? en.value : '未知'
          }
          return item[headers[key]]
        })
      })
      console.log(arr)
      return arr
    }
  }
}
</script>

<style lang="scss" scoped></style>
